<template>
  <view>
    <view class="cart_list">
      <!-- 循环是单独的 每一项！！不是总的大项！！ -->
      <view class="cart_item" v-for="item in cartList" :key="item.goods_id">
        <view class="cart_item_left">
          <!-- 小程序里的单选组件：radio -->
          <!-- checked	Boolean	false	当前是否选中 -->
          <radio
            color="#e8424d"
            class="cart_item_select"
            :checked="item.goods_selected"
            @tap="isSelect(item.goods_id)"
          />
        </view>
        <view class="cart_item_right">
          <GoodsItem :item="item">
            <!-- @tap.stop="使用会阻止事件冒泡" -->
            <view class="cart_count">
              <view
                class="iconfont icon-jianshao"
                @tap.stop="changeCount(item.goods_id, -1)"
              ></view>
              <text class="cart_count_text">{{ item.goods_count }}</text>
              <view
                class="iconfont icon-zengjia"
                @tap.stop="changeCount(item.goods_id, 1)"
              ></view>
            </view>
          </GoodsItem>
        </view>
      </view>
    </view>
    <!-- 底部固定栏 -->
    <view class="bottom" v-if="cartList.length">
      <radio
        class="bottom_select"
        color="#e8424d"
        @tap="changeSelectAllHandle"
        :checked="isSelectAll"
      />
      <text class="selected_all">全选</text>
      <text class="totals_text">合计：</text>
      <text class="totals_price price">{{ totalPrice }}</text>
      <view class="account" @tap="gotoPayHandle">去结算（{{ account }}）</view>
    </view>
    <!-- 购物车为空时的样式、状态 -->
    <view v-if="cartList.length === 0" class="cart_empty">
      <!-- <view class="cart_empty"> -->
      <image
        src="../../static/cart_empty.gif"
        mode="widthFix"
        class="empty_image"
      />
      <navigator
        url="../index/main"
        open-type="switchTab"
        hover-class="none"
        class="empty_button"
        >去首页看看</navigator
      >
    </view>
  </view>
</template>

<script>
import GoodsItem from "@/components/GoodsItem/index.vue";
export default {
  components: {
    GoodsItem,
  },
  data() {
    return {
      cartList: [{}],
    };
  },
  onShow() {
    // onShow 获取购物车列表
    // 一定要赋值！！！赋值
    this.cartList = uni.getStorageSync("cartList") || [];
  },
  computed: {
    // 如果是要计算出一个新的变量，就要用计算属性：
    isSelectAll() {
      // 如果购物车列表里面每一个都选中的话，那么 下面的全选标记也会跟着被选中！！
      return this.cartList.every((item) => item.goods_selected);
    },
    totalPrice() {
      let totalPrice = 0;
      this.cartList.forEach((item) => {
        if (item.goods_selected) {
          // 如果选中就计算：
          totalPrice += item.goods_price * item.goods_count;
        }
      });
      return totalPrice;
    },
    account() {
      let account = 0;
      // 淘宝算法：
      // this.cartList.forEach((item) => {
      //   if (item.goods_selected) {
      //     account++;
      //   }
      // });

      // 京东算法：
      this.cartList.forEach((item) => {
        if (item.goods_selected) {
          account += item.goods_count;
        }
      });
      return account;
    },
  },
  watch: {
    // 监听goods_count的变化：
    cartList: {
      deep: true,
      // 是对象！！是用冒号连接的
      handler: (val) => {
        // 把值给存到本地里面去
        uni.setStorageSync("cartList", val);
      },
    },
  },
  methods: {
    // 改变选中状态：
    isSelect(goods_id) {
      // 参数不要是index因为  增删改查，就会变化的！！
      // 通过findIndex寻找索引：
      const index = this.cartList.findIndex(
        (item) => item.goods_id === goods_id
      );
      // 选中状态取反
      this.cartList[index].goods_selected = !this.cartList[index]
        .goods_selected;
    },
    changeCount(goods_id, number) {
      const index = this.cartList.findIndex(
        // 这样只更新了data里的数据，但是并没有同步本地存储里的数据
        // (item) => item.goods_id === this.goods_id   不要this！！！
        (item) => item.goods_id === goods_id
      );
      // 如果是减号的情况：且goods_count 为1时：
      if (number === -1 && this.cartList[index].goods_count === 1) {
        // 就弹出一个 模态框：
        uni.showModal({
          // title: "提示",
          content: "是否从购物车移出该商品？？",
          confirmText: "删除",
          confirmColor: "#ccc",
          success: (res) => {
            if (res.confirm) {
              // 点击确定就是说明用户删除了数据   不能用普通函数！！要改成箭头函数！否则会影响this指向！！
              this.cartList.splice(index, 1);
              console.log("用户点击确定");
            }
            // 取消就不用处理操作
          },
        });
      } else {
        this.cartList[index].goods_count += number;
      }
    },
    changeSelectAllHandle() {
      // 当点击下方的全选按钮！也能够影响上面的小按钮的选中状态：
      const bl = !this.isSelectAll;
      // 遍历购物车里的列表，使其中的每一项都改变状态！！
      this.cartList.forEach((item) => {
        item.goods_selected = bl; //不要return
      });
    },
    gotoPayHandle() {
      // 如果结算的数量为0；则弹窗提示：
      if (this.account === 0) {
        uni.showToast({
          title: "购物车空空如也，再看看呗",
          icon: "none",
          duration: 2000,
        });
      } else {
        uni.navigateTo({
          url: "../pay/main",
        });
      }
    },
  },
};
</script>

<style lang="less" >
.cart_list {
  .cart_item {
    display: flex;
    padding: 0 20rpx;
    border-bottom: 1rpx solid #ddd;
    &:last-child {
      border-bottom: none;
    }
    .cart_item_left {
      width: 78rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      // .cart_item_select {
      // }
    }

    .cart_item_right {
      flex: 1;
      position: relative;
      .cart_count {
        position: absolute;
        right: 30rpx;
        bottom: 30rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        .iconfont {
          font-size: 40rpx;
          color: #666;
        }

        .cart_count_text {
          padding: 0 20rpx;
          text-align: center;
          min-width: 50rpx; // 用最小宽度确保大部分情况下都是对齐的，特殊情况也能正常显示数字
        }

        .icon-zengjia {
          font-size: 34rpx;
        }
      }
    }
  }
}
.bottom {
  height: 88rpx;
  padding: 0 20rpx;
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border-top: 1rpx solid #dddddd;
  box-sizing: border-box;

  .selected_all {
    margin-left: 18rpx;
    color: #999;
    font-size: 23rpx;
  }

  .totals_text {
    margin-left: 20rpx;
    font-size: 26rpx;
  }

  .price {
    flex: 1;
    margin-left: 10rpx;
    font-size: 28rpx;
  }

  .account {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 18rpx;
    width: 150rpx;
    height: 52rpx;
    background-color: var(--mainColor);
    border-radius: 50rpx;
    color: #ffffff;
    font-size: 22rpx;
  }
}
// 当购物车为空时：
.cart_empty {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100vw;
  height: 100vh;
  .empty_image {
    width: 400rpx;
  }

  .empty_button {
    margin-top: 20rpx;
    width: 200rpx;
    height: 60rpx;
    color: #fff;
    background-color: var(--mainColor);
    border-radius: 30rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 22rpx;
  }
}
</style>